var timer = null // 定时器

Page({
  P: [8, 16, 25, 34, 42, 50, 58, 66, 75, 86, 92, 100],
  C: ["#f00", "#f90", "#ff0", "#9f0", "#0f0", "#0f9", "#0ff", "#09f", "#00f", "#90f", "#f0f", "#f09"],

  data: {
    isRand: true,
    percent: null,
    color: null
  },

  randColor: function () {
    var r = Math.floor(Math.random() * 255)
    var g = Math.floor(Math.random() * 255)
    var b = Math.floor(Math.random() * 255)
    return 'rgb(' + r + ', ' + g + ', ' + b + ')'
  },

  onReady: function () {
    this.resetWave()
  },

  setRand: function (e) {
    this.setData({
      isRand: e.detail.value
    })
  },

  randWave: function () {
    var percent = []
    var color = []
    for (var i = 0; i < 12; i++) {
      var rnd = Math.round(Math.random() * 100)
      percent[i] = rnd
      color[i] = this.randColor()
    }
    this.setData({
      percent: percent,
      color: color
    })
  },

  stepWave: function () {
    var percent = this.data.percent
    var color = this.data.color
    for (var i = 0; i < 11; i++) {
      percent[i] = percent[i + 1]
      color[i] = color[i + 1]
    }
    percent[11] = Math.floor(Math.random() * 101)
    color[11] = this.randColor()
    this.setData({
      percent: percent,
      color: color
    })
  },

  manualWave: function () {
    clearTimeout(timer)
    if (this.data.isRand) {
      this.randWave()
    } else {
      this.stepWave()
    }
  },

  autoWave: function () {
    clearTimeout(timer)
    if (this.data.isRand) {
      this.randWave()
    } else {
      this.stepWave()
    }
    timer = setTimeout(this.autoWave, 300)
  },

  resetWave: function () {
    clearTimeout(timer)
    this.setData({
      percent: this.P,
      color: this.C
    })
  }
})